<template>
  <div class="home-container">
    <!-- 搜索和筛选区域 -->
    <div class="search-section">
      <div class="container">
        <div class="search-header">
          <div class="search-bar">
            <a-input-search
              v-model:value="searchParams.searchText"
              placeholder="搜索图片..."
              size="large"
              @search="handleSearch"
              enter-button
            >
              <template #prefix>
                <SearchOutlined />
              </template>
            </a-input-search>
          </div>
          <div class="upload-btn" v-if="userStore.isLogin">
            <a-button type="primary" size="large" @click="showUploadModal = true">
              <template #icon>
                <CloudUploadOutlined />
              </template>
              上传图片
            </a-button>
          </div>
        </div>

        <!-- 筛选标签 -->
        <div class="filter-section">
          <!-- 分类筛选 -->
          <div class="filter-item">
            <span class="filter-label">分类：</span>
            <a-tag
              :color="!selectedCategory ? '#1890ff' : 'default'"
              @click="handleCategoryChange('')"
              class="filter-tag"
            >
              全部
            </a-tag>
            <a-tag
              v-for="category in categoryList"
              :key="category"
              :color="selectedCategory === category ? '#1890ff' : 'default'"
              @click="handleCategoryChange(category)"
              class="filter-tag"
            >
              {{ category }}
            </a-tag>
          </div>

          <div class="filter-item">
            <span class="filter-label">标签：</span>
            <a-tag
              v-for="tag in tagList"
              :key="tag"
              :color="selectedTags.includes(tag) ? '#1890ff' : 'default'"
              @click="handleTagChange(tag)"
              class="filter-tag"
            >
              {{ tag }}
            </a-tag>
          </div>
        </div>
      </div>
    </div>

    <!-- 图片展示区域 -->
    <div class="pictures-section">
      <div class="container">
        <a-spin :spinning="loading" size="large">
          <!-- 瀑布流布局 -->
          <div class="waterfall-container" ref="waterfallRef">
            <div
              v-for="picture in pictureList"
              :key="picture.id"
              class="picture-item"
              @click="handlePictureClick(picture)"
            >
              <div class="picture-card">
                <div class="picture-image">
                  <img
                    :src="picture.thumbnailUrl || picture.url"
                    :alt="picture.name"
                    @load="handleImageLoad"
                    @error="handleImageError"
                  />
                </div>
                <div class="picture-info">
                  <h3 class="picture-title">{{ picture.name }}</h3>
                  <p class="picture-description" v-if="picture.introduction">
                    {{ picture.introduction }}
                  </p>
                  <div class="picture-meta">
                    <div class="picture-tags" v-if="picture.tags && picture.tags.length > 0">
                      <a-tag v-for="tag in picture.tags.slice(0, 3)" :key="tag" size="small">
                        {{ tag }}
                      </a-tag>
                      <span v-if="picture.tags.length > 3" class="more-tags">
                        +{{ picture.tags.length - 3 }}
                      </span>
                    </div>
                    <div class="picture-author" v-if="picture.userVO">
                      <a-avatar
                        :size="20"
                        :src="picture.userVO.userAvatar"
                        :alt="picture.userVO.userName"
                      />
                      <span class="author-name">{{
                        picture.userVO.userName || picture.userVO.userAccount
                      }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 加载更多 -->
          <div class="load-more" v-if="hasMore && !loading">
            <a-button @click="loadMore" size="large" block> 加载更多 </a-button>
          </div>

          <!-- 没有更多数据 -->
          <div class="no-more" v-if="!hasMore && pictureList.length > 0">
            <a-divider>没有更多图片了</a-divider>
          </div>

          <!-- 空状态 -->
          <a-empty v-if="!loading && pictureList.length === 0" description="暂无图片" />
        </a-spin>
      </div>
    </div>

    <!-- 图片上传模态框 -->
    <a-modal v-model:open="showUploadModal" title="上传图片" width="600px" :footer="null">
      <picture-upload-form @success="handleUploadSuccess" @cancel="showUploadModal = false" />
    </a-modal>

    <!-- 图片详情模态框 -->
    <a-modal
      v-model:open="showDetailModal"
      :title="selectedPicture?.name"
      width="80%"
      :footer="null"
      centered
    >
      <div class="picture-detail" v-if="selectedPicture">
        <div class="detail-image">
          <img :src="selectedPicture.url" :alt="selectedPicture.name" />
        </div>
        <div class="detail-info">
          <div class="info-item">
            <span class="info-label">图片名称：</span>
            <span>{{ selectedPicture.name }}</span>
          </div>
          <div class="info-item" v-if="selectedPicture.introduction">
            <span class="info-label">图片简介：</span>
            <span>{{ selectedPicture.introduction }}</span>
          </div>
          <div class="info-item" v-if="selectedPicture.category">
            <span class="info-label">分类：</span>
            <a-tag>{{ selectedPicture.category }}</a-tag>
          </div>
          <div class="info-item" v-if="selectedPicture.tags && selectedPicture.tags.length > 0">
            <span class="info-label">标签：</span>
            <div class="tags-container">
              <a-tag v-for="tag in selectedPicture.tags" :key="tag">{{ tag }}</a-tag>
            </div>
          </div>
          <div class="info-item" v-if="selectedPicture.userVO">
            <span class="info-label">上传者：</span>
            <a-avatar
              :size="24"
              :src="selectedPicture.userVO.userAvatar"
              :alt="selectedPicture.userVO.userName"
            />
            <span class="author-name">{{
              selectedPicture.userVO.userName || selectedPicture.userVO.userAccount
            }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">上传时间：</span>
            <span>{{ formatTime(selectedPicture.createTime) }}</span>
          </div>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { message } from 'ant-design-vue'
import { CloudUploadOutlined, SearchOutlined } from '@ant-design/icons-vue'
import { useUserStore } from '@/stores/user'
import { listPictureVOByPage, listPictureTagCategory } from '@/api/picture'
import type { PictureVO, PictureQueryRequest } from '@/types/picture'
import { PictureUploadForm } from '@/components'

const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const pictureList = ref<PictureVO[]>([])
const tagList = ref<string[]>([])
const categoryList = ref<string[]>([])
const hasMore = ref(true)
const showUploadModal = ref(false)
const showDetailModal = ref(false)
const selectedPicture = ref<PictureVO | null>(null)
const waterfallRef = ref<HTMLElement>()

// 搜索和筛选参数
const searchParams = reactive<PictureQueryRequest>({
  current: 1,
  pageSize: 20,
  searchText: '',
  nullSpaceId: true, // 只查询公共图片
})

const selectedCategory = ref('')
const selectedTags = ref<string[]>([])

// 初始化数据
onMounted(async () => {
  await loadTagsAndCategories()
  await loadPictures(true)
})

// 加载标签和分类
const loadTagsAndCategories = async () => {
  try {
    const response = await listPictureTagCategory()
    if (response.data) {
      tagList.value = response.data.tagList || []
      categoryList.value = response.data.categoryList || []
    }
  } catch (error) {
    console.error('加载标签和分类失败:', error)
  }
}

// 加载图片列表
const loadPictures = async (reset = false) => {
  if (loading.value) return

  loading.value = true
  try {
    // 重置时清空列表并重置页码
    if (reset) {
      pictureList.value = []
      searchParams.current = 1
      hasMore.value = true
    }

    // 构建查询参数
    const queryParams: PictureQueryRequest = {
      ...searchParams,
      category: selectedCategory.value || undefined,
      tags: selectedTags.value.length > 0 ? selectedTags.value : undefined,
    }

    const response = await listPictureVOByPage(queryParams)

    if (response.data) {
      const { records, current, total, size } = response.data

      if (reset) {
        pictureList.value = records
      } else {
        pictureList.value.push(...records)
      }

      // 判断是否还有更多数据
      hasMore.value = current * size < total

      // 如果有更多数据，准备下一页
      if (hasMore.value) {
        searchParams.current = current + 1
      }

      // 图片加载完成后重新布局瀑布流
      await nextTick()
      layoutWaterfall()
    }
  } catch (error) {
    console.error('加载图片失败:', error)
    message.error('加载图片失败')
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  loadPictures(true)
}

// 分类筛选
const handleCategoryChange = (category: string) => {
  selectedCategory.value = category
  loadPictures(true)
}

// 标签筛选
const handleTagChange = (tag: string) => {
  const index = selectedTags.value.indexOf(tag)
  if (index > -1) {
    selectedTags.value.splice(index, 1)
  } else {
    selectedTags.value.push(tag)
  }
  loadPictures(true)
}

// 加载更多
const loadMore = () => {
  loadPictures(false)
}

// 图片点击处理
const handlePictureClick = (picture: PictureVO) => {
  selectedPicture.value = picture
  showDetailModal.value = true
}

// 图片加载完成处理
const handleImageLoad = () => {
  // 图片加载完成后重新布局
  nextTick(() => {
    layoutWaterfall()
  })
}

// 图片加载错误处理
const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement
  img.src = '/api/placeholder/300/200' // 设置默认图片
}

// 上传成功处理
const handleUploadSuccess = () => {
  showUploadModal.value = false
  // 重新加载图片列表
  loadPictures(true)
}

// 瀑布流布局
const layoutWaterfall = () => {
  if (!waterfallRef.value) return

  const container = waterfallRef.value
  const items = container.querySelectorAll('.picture-item') as NodeListOf<HTMLElement>

  if (items.length === 0) return

  const containerWidth = container.offsetWidth
  const itemWidth = 280 // 固定宽度
  const gap = 16 // 间距
  const cols = Math.floor((containerWidth + gap) / (itemWidth + gap))

  // 初始化列高度数组
  const colHeights = new Array(cols).fill(0)

  items.forEach((item) => {
    const img = item.querySelector('img') as HTMLImageElement
    const info = item.querySelector('.picture-info') as HTMLElement

    // 计算图片高度
    let imgHeight = 200 // 默认高度
    if (img && img.complete && img.naturalHeight > 0) {
      imgHeight = (img.naturalHeight / img.naturalWidth) * itemWidth
    }

    // 计算信息区域高度
    const infoHeight = info ? info.offsetHeight : 80
    const totalHeight = imgHeight + infoHeight + 16 // 加上内边距

    // 找到最短的列
    const minColIndex = colHeights.indexOf(Math.min(...colHeights))
    const left = minColIndex * (itemWidth + gap)
    const top = colHeights[minColIndex]

    // 设置位置
    item.style.position = 'absolute'
    item.style.left = `${left}px`
    item.style.top = `${top}px`
    item.style.width = `${itemWidth}px`

    // 更新列高度
    colHeights[minColIndex] += totalHeight + gap
  })

  // 设置容器高度
  const maxHeight = Math.max(...colHeights)
  container.style.height = `${maxHeight}px`
}

// 格式化时间
const formatTime = (timeStr?: string) => {
  if (!timeStr) return ''
  const date = new Date(timeStr)
  return date.toLocaleString('zh-CN')
}

// 监听窗口大小变化，重新布局
window.addEventListener('resize', () => {
  nextTick(() => {
    layoutWaterfall()
  })
})
</script>

<style scoped>
.home-container {
  min-height: calc(100vh - 64px);
  background: #f8f9fa;
}

.container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 24px;
}

/* 搜索区域 */
.search-section {
  background: white;
  padding: 24px 0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  margin-bottom: 24px;
}

.search-header {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 20px;
}

.search-bar {
  flex: 1;
  max-width: 600px;
}

.upload-btn {
  flex-shrink: 0;
}

/* 筛选区域 */
.filter-section {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.filter-item {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
}

.filter-label {
  font-weight: 500;
  color: #262626;
  white-space: nowrap;
  margin-right: 8px;
}

.filter-tag {
  cursor: pointer;
  transition: all 0.3s ease;
  user-select: none;
}

.filter-tag:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 图片展示区域 */
.pictures-section {
  padding: 0 0 40px 0;
}

/* 瀑布流容器 */
.waterfall-container {
  position: relative;
  width: 100%;
  min-height: 400px;
}

.picture-item {
  position: absolute;
  cursor: pointer;
  transition: transform 0.3s ease;
}

.picture-item:hover {
  transform: translateY(-4px);
}

.picture-card {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  transition: box-shadow 0.3s ease;
}

.picture-card:hover {
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.picture-image {
  position: relative;
  overflow: hidden;
}

.picture-image img {
  width: 100%;
  height: auto;
  display: block;
  transition: transform 0.3s ease;
}

.picture-card:hover .picture-image img {
  transform: scale(1.05);
}

.picture-info {
  padding: 16px;
}

.picture-title {
  font-size: 16px;
  font-weight: 600;
  margin: 0 0 8px 0;
  color: #262626;
  line-height: 1.4;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.picture-description {
  font-size: 14px;
  color: #666;
  margin: 0 0 12px 0;
  line-height: 1.5;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  line-clamp: 2;
}

.picture-meta {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.picture-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  align-items: center;
}

.more-tags {
  font-size: 12px;
  color: #999;
}

.picture-author {
  display: flex;
  align-items: center;
  gap: 6px;
}

.author-name {
  font-size: 12px;
  color: #666;
}

/* 加载更多 */
.load-more {
  margin-top: 40px;
}

.no-more {
  margin-top: 40px;
}

/* 图片详情模态框 */
.picture-detail {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.detail-image {
  text-align: center;
}

.detail-image img {
  max-width: 100%;
  max-height: 60vh;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.detail-info {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.info-item {
  display: flex;
  align-items: flex-start;
  gap: 8px;
}

.info-label {
  font-weight: 500;
  color: #262626;
  white-space: nowrap;
  min-width: 80px;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .container {
    max-width: 1000px;
  }
}

@media (max-width: 768px) {
  .container {
    padding: 0 16px;
  }

  .search-header {
    flex-direction: column;
    align-items: stretch;
  }

  .search-bar {
    max-width: none;
  }

  .filter-item {
    flex-direction: column;
    align-items: flex-start;
  }

  .filter-label {
    margin-bottom: 4px;
  }

  .picture-detail {
    gap: 16px;
  }

  .info-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }

  .info-label {
    min-width: auto;
  }
}

@media (max-width: 480px) {
  .container {
    padding: 0 12px;
  }

  .search-section {
    padding: 16px 0;
  }

  .picture-info {
    padding: 12px;
  }

  .picture-title {
    font-size: 14px;
  }

  .picture-description {
    font-size: 12px;
  }
}

/* Ant Design 组件样式覆盖 */
:deep(.ant-input-search) {
  .ant-input {
    border-radius: 8px;
  }

  .ant-btn {
    border-radius: 0 8px 8px 0;
  }
}

:deep(.ant-tag) {
  border-radius: 6px;
  border: none;
  font-size: 12px;
}

:deep(.ant-modal-content) {
  border-radius: 12px;
}

:deep(.ant-modal-header) {
  border-radius: 12px 12px 0 0;
}

:deep(.ant-spin-container) {
  min-height: 200px;
}
</style>
